﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;

namespace MikeKappel.Com.CS.HttpModules
{
    /// <summary>
    /// Summary description for GoogleAnalytics
    /// Google Analytics Http Filter
    /// </summary>
    public class GoogleAnalyticsFilter : MikeKappel.Com.CS.HttpModules.StreamFilter.IFilterer
    {
        #region Properties

        public enum AnalyticsModeType
        {
            MultiDomain,
            SingleDomain,
            MultiSubdomain
        }

        /// <summary>
        /// Website Domain
        /// </summary>
        public String Domain
        {
            get
            {
                if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["GoogleAnalyticsDomain"]))
                    throw new Exception("GoogleAnalyticsDomain required in Web.Config to use GoogleAnalyticsFilter");

                return ConfigurationManager.AppSettings["GoogleAnalyticsDomain"]; ;
            }
        }

        /// <summary>
        /// Web Property ID
        /// </summary>
        public String WebPropertyID
        {
            get
            {
                if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["GoogleAnalyticsWebPropertyID"]))
                    throw new Exception("GoogleAnalyticsWebPropertyID required in Web.Config to use GoogleAnalyticsFilter");

                return ConfigurationManager.AppSettings["GoogleAnalyticsWebPropertyID"];
            }
        }

        /// <summary>
        /// Web Property ID
        /// </summary>
        public AnalyticsModeType AnalyticsMode
        {
            get
            {
                try
                {
                    return (AnalyticsModeType)Enum.Parse(typeof(AnalyticsModeType), ConfigurationManager.AppSettings["GoogleAnalyticsMode"]);
                }
                catch (Exception ex)
                {
                    throw new Exception("GoogleAnalyticsMode required in Web.Config to use GoogleAnalyticsFilter and must be \"MultiDomain\",\"SingleDomain\", or \"MultiSubdomain\"\n" + ex.Message);
                }
            }
        }


        /// <summary>
        /// Tracking Multi-Top Level Domains
        /// </summary>
        public String JavaScriptTrackingMultiTopLevel
        {
            get
            {
                return "<script type=\"text/javascript\">" +
                    "\n     var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");" +
                    "\n     document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));" +
                    "\n  </script>" +
                    "\n  <script type=\"text/javascript\">" +
                    "\n    try {" +
                    "\n         var pageTracker = _gat._getTracker(\"" + WebPropertyID + "\");" +
                    "\n         pageTracker._setDomainName(\"none\");" +
                    "\n         pageTracker._setAllowLinker(true);" +
                    "\n         pageTracker._trackPageview();" +
                    "\n    } catch(err) {}" +
                    "\n</script>\n";
            }
        }

        /// <summary>
        /// Tracking One domain with multiple subdomains
        /// </summary>
        public String JavaScriptTrackingMultiSubdomains
        {
            get
            {
                return "<script type=\"text/javascript\">" +
                    "\n     var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");" +
                    "\n     document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));" +
                    "\n </script>" +
                    "\n <script type=\"text/javascript\">" +
                    "\n     try {" +
                    "\n     var pageTracker = _gat._getTracker(\"" + WebPropertyID + "\");" +
                    "\n     pageTracker._setDomainName(\"." + Domain + "\");" +
                    "\n     pageTracker._trackPageview();" +
                    "\n     } catch(err) {}" +
                    "\n </script>\n";
            }
        }

        /// <summary>
        /// Tracking a single domain with multiple subdomains
        /// </summary>
        public String JavaScriptTrackingSingleDomain
        {
            get
            {
                return "<script type=\"text/javascript\">" +
                    "\n     var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");" +
                    "\n     document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));" +
                    "\n </script>" +
                    "\n <script type=\"text/javascript\">" +
                    "\n     try {" +
                    "\n     var pageTracker = _gat._getTracker(\"" + WebPropertyID + "\");" +
                    "\n     pageTracker._trackPageview();" +
                    "\n     } catch(err) {}" +
                    "\n </script>\n";
            }
        }
        #endregion
        #region Constructors
        public GoogleAnalyticsFilter()
        {
        }
        #endregion
        #region Methods
        public String Filter(String unfiltered)
        {
            String filtered = unfiltered;
            if (AnalyticsMode == AnalyticsModeType.MultiDomain)
               if (!filtered.Contains(JavaScriptTrackingMultiTopLevel))
                    filtered = filtered.Replace("</body>", JavaScriptTrackingMultiTopLevel + "</body>");
            else if(AnalyticsMode == AnalyticsModeType.MultiSubdomain)
               if (!filtered.Contains(JavaScriptTrackingMultiSubdomains))
                    filtered = filtered.Replace("</body>", JavaScriptTrackingMultiSubdomains + "</body>");
            else
               if (!filtered.Contains(JavaScriptTrackingSingleDomain))
                   filtered = filtered.Replace("</body>", JavaScriptTrackingSingleDomain + "</body>");

            return filtered;
        }
        #endregion
    }
}

